const db = require('../core/index')
const moment = require('moment')
// 加密
const md5 = require('md5')
const fs = require('node:fs')

// json web token
const jwt = require('jwt-simple')
const path = require('node:path')
class userController {
    async register (req, res, next) {
        console.log(req.body)
        const data = [
            req.body.name,
            // 第一次加密
            md5(req.body.psd + require('../config/index').tokenKey),
            req.body.sex || 1,
            moment().format('YYYY-MM-DD hh:mm:ss')
        ]
        console.log('data', data)
        const sql = 'insert into user(u_name,u_psd,u_sex,u_create) values(?,?,?,?)'
        try {
            const result = await db(sql, data)
            if (result && result.affectedRows === 1) {
                res.json({
                    code: '200',
                    msg: '注册成功',
                    data: true
                })
            } else {
                res.json({
                    code: '200',
                    msg: '注册失败',
                    data: false
                })
            }
        } catch (error) {
            res.json({
                code: '500',
                msg: '服务器异常',
                data: false
            })
        }
    }
    async login (req, res, next) {
        function createToken (value) {
            return jwt.encode({
                exp: Date.now() + (1000 * 60 * 24),
                info: value
            }, require('../config/index').tokenKey)
        }
        const data = [
            req.body.name,
            // 第二次加密
            md5(req.body.psd + require('../config/index').tokenKey),
        ]
        console.log(data)
        const sql = 'select u_id,u_name,u_create,u_sex from user where u_name=? and u_psd=? and u_isDelete=1'
        try {
            const result = await db(sql, data)
            console.log('result', result)
            if (result && result.length > 0) {
                res.json({
                    code: 200,
                    msg: '登陆成功',
                    data: { ...result[0], u_create: moment(result[0].u_create).format('YYYY-MM-DD hh:mm:ss') },
                    token: createToken(result && result[0])
                })
            } else {
                res.json({
                    code: 200,
                    msg: '登陆失败',
                    data: false
                })
            }
        } catch (error) {
            console.log(error)
            res.json({
                code: 500,
                msg: '服务器错误',
                data: false
            })
        }
    }
    // sql 语句 根据动态参数进行查询 
    async selectIn (req, res, next) {
        try {
            const uids = JSON.parse(req.body.uids)
            const queryUids = uids.map(item => '?')
            console.log(queryUids)
            const sql = `select * from user where u_id in (${queryUids.slice(',')})`
            console.log(sql)
            const result = await db(sql, uids)
            if (result && result.length > 0) {
                res.json({
                    code: 200,
                    data: result,
                    msg: '查询成功'
                })
            } else {
                res.json({
                    code: 1010,
                    data: result,
                    msg: '查询失败'
                })
            }
        } catch (error) {
            console.log(error)
            res.json({
                code: 500,
                data: null,
                msg: error.message
            })
        }
    }
    regPage (req, res, next) {
        const regPage = fs.readFileSync(path.resolve(__dirname, '../view/reg.ejs'))
        // console.log(regPage.toString())
        res.setHeader('content-type', 'text/html;carset=utf-8')
        res.send(regPage.toString())
    }
    loginPage (req, res, next) {
        const regPage = fs.readFileSync(path.resolve(__dirname, '../view/login.ejs'))
        // console.log(regPage.toString())
        res.setHeader('content-type', 'text/html;carset=utf-8')
        res.send(regPage.toString())
    }
}

module.exports = new userController()